package com.toymate.ai.tts.model.reecho;

import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import com.toymate.ai.tts.AbstractTtsService;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Optional;

/**
 * ReechoTtsService
 *
 * @author weirdor (179946422@qq.com)
 * @version v1.0.0
 */
@Slf4j
public class ReechoTtsService extends AbstractTtsService {

    private JSONObject sttConfig;

    public ReechoTtsService(JSONObject role) {
        this.sttConfig = role.getJSONObject("tts_config");
    }

    /**
     * 文字转换语音
     *
     * @param content 转换的文字
     * @return Optional<String> 文件路径
     */
    @Override
    public Optional<String> speechSynthesizer(String id, String content) {
        String key = sttConfig.getStr("key");
        String voiceId = sttConfig.getStr("voice_id");
        Map<String, Object> paramMap = MapUtil.newHashMap();
        paramMap.put("voiceId", voiceId);
        paramMap.put("text", content);
        paramMap.put("flash", true);
        paramMap.put("stream", false);
        JSONObject jsonObject = new JSONObject(paramMap);
        HttpResponse response = HttpUtil.createPost("https://v1.reecho.cn/api/tts/simple-generate")
                .header("Authorization", "Bearer " + key)
                .body(jsonObject.toString())
                .execute();
        if (response.isOk()) {
            JSONObject result = new JSONObject(response.body());
            String data = result.getJSONObject("data").getStr("audio");
            return Optional.of(data);
        } else {
            log.error("ReechoTtsService error: {}", response.body());
            return Optional.empty();
        }
    }
}
